<template>
  <div class="boos-category">
    <el-row>
      <el-col :span="8">
        <el-table :data="categoryData.cate1" height="750" stripe highlight-current-row @row-click="onCate1Click"
                  v-loading="loading">
          <el-table-column prop="catName" label="一级分类">
            <template #header>
              <span class="title">一级分类</span>
              <div class="query">
                <el-input placeholder="请输入内容" v-model="categoryData.search.cateName1" class="input-with-select"
                          clearable>
                  <template #append>
                    <el-button @click="onCate1SearchClick()">
                      <el-icon>
                        <Search />
                      </el-icon>
                    </el-button>
                  </template>
                </el-input>
                <Button v-if="isShow" label="新增" type="primary" plain @click="onAddClick(1)" />
              </div>
            </template>
            <template #default="scope">
              <span> {{ scope.row.catName }}</span>
              <span class="goods-count">
                {{ scope.row.goodsCount }}
              </span>
            </template>
          </el-table-column>

          <el-table-column width="100">
            <template #default="scope">
              <Link v-if="isShow" label="修改" @click.stop="onEditClick(scope.row, 1)" />
              <Link v-if="isShow" label="删除" @click.stop="onDelClick(scope.row, 1)" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8">
        <el-table :data="categoryData.cate2" height="750" stripe highlight-current-row @row-click="onCate2Click"
                  v-loading="loading" :cell-class-name="tableCellClassName">
          <el-table-column prop="catName" label="二级分类">
            <template #header>
              <span class="title">二级分类</span>
              <div class="query">
                <el-input placeholder="请输入内容" v-model="categoryData.search.cateName2" class="input-with-select"
                          clearable>
                  <template #append>
                    <el-button type="primary" plain @click="onCate2SearchClick()">
                      <el-icon>
                        <Search />
                      </el-icon>
                    </el-button>
                  </template>
                </el-input>
                <Button v-if="isShow" label="新增" type="primary" plain :disabled="!categoryData.curCate1.catId"
                        @click="onAddClick(2)" />
              </div>
            </template>

            <template #default="scope">
              <span> {{ scope.row.catName }}</span>
              <span class="goods-count">
                        {{ scope.row.goodsCount }}
                      </span>
            </template>
          </el-table-column>

          <el-table-column width="100">
            <template #default="scope">
              <Link v-if="isShow" label="修改" @click.stop="onEditClick(scope.row, 2)" />
              <Link v-if="isShow" label="删除" @click.stop="onDelClick(scope.row, 2)" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col :span="8">
        <el-table :data="categoryData.cate3" height="750" stripe highlight-current-row v-loading="loading"
                  :cell-class-name="tableCellClassName">
          <el-table-column prop="catName" label="三级分类">
            <template #header>
              <span class="title">三级分类</span>
              <div class="query">
                <el-input placeholder="请输入内容" v-model="categoryData.search.cateName3" class="input-with-select"
                          clearable>
                  <template #append>
                    <el-button type="primary" plain @click="onCate3SearchClick()">
                      <el-icon>
                        <Search />
                      </el-icon>
                    </el-button>
                  </template>
                </el-input>
                <Button v-if="isShow" label="新增" type="primary" plain :disabled="!categoryData.curCate2.catId"
                        @click="onAddClick(3)" />
              </div>
            </template>

            <template #default="scope">
              <span> {{ scope.row.catName }}</span>
              <span class="goods-count">
                  {{ scope.row.goodsCount }}
              </span>
            </template>
          </el-table-column>

          <el-table-column width="190">
            <template #default="scope">
              <Link v-if="isShow" label="导入" @click.stop="onImportClick(scope.row, 3)" />
              <Link v-if="isShow" label="修改" @click.stop="onEditClick(scope.row, 3)" />
              <Link v-if="isShow" label="删除" @click.stop="onDelClick(scope.row, 3)" />
              <Link v-if="isShow" label="属性管理" @click.stop="onTagClick(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-dialog :title="`${dialogTitle}`" v-model="categoryVisible" :close-on-click-modal="false" width="30%"
               @close="closeDialog">
      <el-form ref="categoryFormRef" :model="categoryData.form" label-width="80px" label-position="left"
               :status-icon="true" :show-message="false">
        <el-form-item label="分类名称" prop="categoryName" required>
          <el-input v-model="categoryData.form.categoryName" autocomplete="off" placeholder="请输入分类名称"
                    clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <Button label="取消" @click="onCancelClick" />
        <Button label="确认" type="primary" @click="onSubmitClick" />
      </template>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" width="30%" v-model="importVisible"
               @close="closeImportDialog">

      <el-upload
        ref="upload"
        :limit="1"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :auto-upload="false">
        <template #trigger>
          <el-button type="primary">点击上传文件</el-button>
        </template>
      </el-upload>

      <template #footer>
        <Button label="取消" @click="closeImportDialog" />
        <Button label="确认" type="primary" @click="onSumbitImport" />
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { nextTick, reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowRight } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import api from '@/api'
import consts from '@/consts'
import { menuStore } from '@/store/menu.js'
import Link from '@/components/button/link.vue'
import Button from '@/components/button/button.vue'

const _menuStore = menuStore()
const route = useRoute()
const router = useRouter()

const categoryData = reactive({
  cate1: [],
  cate2: [],
  cate3: [],

  curCate1: {},
  curCate2: {},

  search: {
    cateName1: '',
    cateName2: '',
    cateName3: ''
  },

  form: {
    level: 1,
    catId: '',
    parId: '',
    categoryName: '',
    categoryId: ''
  }
})

const xlsxData = reactive({
  file: null,
  catId: ''
})

const categoryVisible = ref(false)
const importVisible = ref(false)
const categoryFormRef = ref(null)
const dialogTitle = ref('')
const loading = ref(false)
const isShow = ref(false)
const upload = ref()

const delCate = async (row, level) => {
  let url = `/medinstrument/boss/goodsCategory/delCategory?categoryId=${row.catId}`
  let { err } = await api.post(url)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData(row.parentCatId, '', level, (data) => {
      if (level === 1) {
        categoryData.cate1 = data
        categoryData.cate2 = []
        categoryData.cate3 = []
      } else if (level === 2) {
        categoryData.cate2 = data
        categoryData.cate3 = []
      } else if (level === 3) {
        categoryData.cate3 = data
      }
    })
    ElMessage.success('删除成功')
  }
}

const save = async () => {
  let url = '/medinstrument/boss/goodsCategory/addCategory'
  let params = {}
  if (categoryData.form.categoryId) {
    url = `/medinstrument/boss/goodsCategory/updateCategory?categoryId=${categoryData.form.categoryId}&categoryName=${categoryData.form.categoryName}`
  } else {
    params = {
      catName: categoryData.form.categoryName,
      parentCatId: categoryData.form.parId,
      level: categoryData.form.level
    }
  }
  let { err } = await api.post(url, params)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData(categoryData.form.parId, '', categoryData.form.level, (data) => {
      if (categoryData.form.parId === '0' && categoryData.form.level === 1) {
        categoryData.cate1 = data
      } else if (categoryData.form.parId === 0 && categoryData.form.level === 1) {
        categoryData.cate1 = data
      } else if (categoryData.form.level === 2) {
        categoryData.cate2 = data
      } else {
        categoryData.cate3 = data
      }
    })

    if (categoryData.form.categoryId) {
      ElMessage.success('修改成功')
    } else {
      ElMessage.success('添加成功')
    }
    closeDialog()
  }
}

const loadData = async (parId, catName, level, callback) => {
  loading.value = true
  let {
    data,
    err
  } = await api.get(`/medinstrument/boss/goodsCategory/getCategory?parId=${parId}&catName=${catName}&level=${level}`)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    callback(data.list)
  }
}

const onCate1Click = (row) => {
  categoryData.cate3 = []
  categoryData.curCate2.catId = ''
  categoryData.curCate1 = row
  loadData(row.catId, '', 2, (data) => (categoryData.cate2 = data))
}

const onCate2Click = (row) => {
  categoryData.curCate2 = row
  loadData(row.catId, '', 3, (data) => (categoryData.cate3 = data))
}

const onAddClick = (level) => {
  categoryData.form.level = level
  categoryData.form.categoryName = ''
  categoryData.form.categoryId = ''
  categoryVisible.value = true
  if (level === 1) {
    categoryData.form.parId = 0
    dialogTitle.value = '一级分类'
  } else if (level === 2) {
    categoryData.form.parId = categoryData.curCate1.catId
    dialogTitle.value = '二级分类'
  } else if (level === 3) {
    categoryData.form.parId = categoryData.curCate2.catId
    dialogTitle.value = '三级分类'
  } else {
    categoryData.form.parId = 0
  }
}

const onEditClick = (row, level) => {
  categoryVisible.value = true
  categoryData.form.parId = row.parentCatId
  categoryData.form.categoryId = row.catId
  categoryData.form.categoryName = row.catName
  categoryData.form.level = level
}

// 导入按钮
const onImportClick = (row) => {
  importVisible.value = true
  xlsxData.catId = row.catId
  if (upload.value) {
    upload.value.clearFiles()
    xlsxData.file = null
  }
}

// 关闭导入弹窗
const closeImportDialog = () => {
  importVisible.value = false
}

// 上传确定按钮
const onSumbitImport = async () => {
  if (!xlsxData.file) {
    ElMessage.error('请先上传Excel文件')
    return
  }
  // 变换成formData数据格式上传
  const formData = new FormData()
  formData.append('file', xlsxData.file)
  formData.append('catId', xlsxData.catId)
  let url = `/medinstrument/boss/importExcel/importExpandparam`
  let { code, message } = await api.post(url, formData)
  if (code === 200) {
    ElMessage.success('导入成功')
    closeImportDialog()
  } else {
    ElMessage.error(message)
  }
}

// 超出上传限制的处理
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

// 上传文件变化处理
const handleChange = (file) => {
  if (file.raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && file.raw.type !== 'application/vnd.ms-excel') {
    ElMessage.error('请上传Excel格式的文件')
    xlsxData.file = null
    upload.value.clearFiles()
    return
  }
  xlsxData.file = file.raw
}

const onDelClick = (row, level) => {
  if (row.goodsCount !== 0) {
    ElMessage.error('此分类含有商品，无法删除')
    return
  }

  ElMessageBox.confirm(`此操作会同时删除分类下所有属性，是否确认删除 ${row.catName}`, '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delCate(row, level)
    })
    .catch(() => {
    })
}

const onTagClick = (row) => {
  let { href } = router.resolve({
    path: `/goods/tag`,
    query: {
      catId: row.catId,
      firstCate: categoryData.curCate1.catName,
      secondCate: categoryData.curCate2.catName,
      thirdCate: row.catName
    }
  })
  window.open(href, '_blank')
}

const onCate1SearchClick = () => {
  loadData(0, categoryData.search.cateName1, 1, (data) => (categoryData.cate1 = data))
}

const onCate2SearchClick = () => {
  if (categoryData.curCate1.catId !== 0) {
    loadData(categoryData.curCate1.catId, categoryData.search.cateName2, 2, (data) => (categoryData.cate2 = data))
  }
}

const onCate3SearchClick = () => {
  if (categoryData.curCate2.catId !== 0) {
    loadData(categoryData.curCate2.catId, categoryData.search.cateName3, 3, (data) => (categoryData.cate3 = data))
  }
}

const onCancelClick = () => {
  closeDialog()
}

const onSubmitClick = () => {
  categoryFormRef.value.validate((valid) => {
    if (valid) {
      save()
    }
  })
}

const closeDialog = () => {
  nextTick(() => {
    categoryFormRef.value.clearValidate()
  })
  categoryVisible.value = false
}

const tableCellClassName = ({ column, columnIndex }) => {
  if (column.property === 'goodsCount') return 'tags'
}

onMounted(() => {
  isShow.value = !!_menuStore.hasAuthorize('/medinstrument/boss/goodsCategory/addCategory')
  loadData(0, '', 1, (data) => (categoryData.cate1 = data))
})
</script>
<style scoped>
.boos-category,
.boos-category .el-row,
.boos-category .el-table {
  height: 100%;
}

.boos-category:deep() .el-table__body tr.current-row > td,
.boos-category:deep() .el-table__body tr.el-table__row--striped.current-row > td {
  background-color: #e4e7ed;
}

.boos-category:deep() .cate1-table .el-table__header .cell {
  padding: 0 10px;
}

.boos-category:deep() .el-table__header {
  height: 120px;
  background-color: #f4f4f5;
  color: #909399;
}

.boos-category:deep() .el-table__header col {
  width: 0;
}

.boos-category:deep() .el-table__header .cell {
  padding: 0;
}

.boos-category:deep() .el-table__header col:first-child {
  width: 100%;
}

.boos-category:deep() .el-table__header .has-gutter tr,
.boos-category:deep() .el-table__header .is-leaf {
  background-color: #fafafa;
}

.boos-category:deep() .el-table td,
.boos-category:deep().el-table th.is-leaf {
  border-bottom: 1px solid #dcdfe6;
}

.boos-category .query {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  padding: 20px 10px 0 10px;
  border-top: 1px solid #dcdfe6;
}

:deep(.el-table__row) .tags {
  display: inline-block;
  padding: 0 6px;
  font-size: 12px;
  background-color: #409eff;
  border-radius: 8px;
  color: #fff;
}

.goods-count {
  padding: 0 6px;
  background-color: #409eff;
  border-radius: 8px;
  color: #fff;
  font-size: 12px;
  line-height: 16px;
  margin-left: 8px;
}

.boos-category .title {
  padding: 0 10px;
}

.boos-category:deep() .el-col {
  border: 1px solid #dcdfe6;
  background: #fff;
}

.boos-category:deep() .el-col:nth-child(2) {
  border-left: 0;
  border-right: 0;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.input-with-select {
  margin-right: 6px;
}

.icon {
  position: absolute;
  right: 5px;
  top: 16px;
}
</style>
